﻿(async () => {
    await window.ris.initialize();

    $(() => {
        const $eventEmitter = $('body > .container');
        let reloadGrid = null;
        let exportParams = null;
        let exportData = (func) => {
            if (func instanceof Function) {
                func(exportParams);
            }
        };
        $('.main').splitter({
            orientation: 'v',
            panel1Size: '300px',
        });
        const quickFilter = $('.quick-filter').quickFilter(
            `/api/filter/get-filter-by-type/exam`,
            filterId => {
                reloadGrid = () => {
                    dataGrid.reload({ filterId });
                };
                reloadGrid();
            },
            {
                type: 'GET',
            }
        );

        const advancedSearch = $('.advanced-search').advancedSearchWithCollapse(null, (e) => {
            reloadGrid = () => {
                dataGrid.refresh({ userData: e });
            };
            reloadGrid();
        }, { id: 'report' });
        const gridOperations = [];
        const gridContextMenuItems = [];
        const dataGrid = $('.exam-grid').examGrid({
            id: 'report-exam-grid',
            key: 'oid',
            getOperations() {
                return gridOperations;
            },
            getContextMenuItems() {
                return gridContextMenuItems;
            },
            onLoad(loadOptions) {
                return new Promise((resolve, reject) => {
                    if (loadOptions.filterId || (loadOptions.userData && !$.isEmptyObject(loadOptions.userData))) {
                        exportParams = loadOptions;
                        $.post({
                            dataType: 'json',
                            contentType: 'application/json;charset=UTF-8',
                            url: `/api/report/get-list`,
                            data: JSON.stringify(loadOptions),
                            success: result => {
                                if (result.success) {
                                    resolve(result)
                                } else {
                                    reject(result.error);
                                }
                            }
                        });
                    } else {
                        resolve({ success: true, data: { columns: [], rows: [], totalCount: 0 } })
                    }
                })
            },
            onRowDblClick(_, row) {
                if (!row.reportId) {
                    DevExpress.ui.notify('当前检查尚未书写报告', 'error');
                }
                else {
                    window.open(`/report/detail?oid=${encodeURIComponent(row.reportId)}`, '_blank');
                }
            },
            masterDetail: {
                enabled: true,
                template: function (container, options) {
                    const $container = $(container);
                    $container.append(`<div class="master-detail"></div>`);
                    const $detail = $container.find('.master-detail');
                    const data = options.data;

                    const $reportStatus = $('<div class="exam-report-status content-item" />').appendTo($detail);
                    $('<span class="title">报告状态：</span>').appendTo($reportStatus);
                    $('<span class="content" />').appendTo($reportStatus).append(window.examGrid.createReportStatusBadge(data.reportStatus, data.isArchive));

                    const $examItems = $('<div class="exam-items content-item" />').appendTo($detail);
                    $('<span class="title">检查项目：</span>').appendTo($examItems);
                    if (data.examItemsText) {
                        $('<span class="content" />').appendTo($examItems).text(data.examItemsText);
                    } else {
                        $('<span class="content">(无)</span>').appendTo($examItems);
                    }

                    const $clinicalDiagnosis = $('<div class="clinical-diagnosis content-item" />').appendTo($detail);
                    $('<span class="title">临床诊断：</span>').appendTo($clinicalDiagnosis);
                    if (data.clinicalDiagnosis) {
                        $('<span class="content" />').appendTo($clinicalDiagnosis).text(data.clinicalDiagnosis);
                    } else {
                        $('<span class="content">(无)</span>').appendTo($clinicalDiagnosis);
                    }

                    const $imageSeeing = $('<div class="image-seeing content-item" />').appendTo($detail);
                    $('<span class="title">影像所见：</span>').appendTo($imageSeeing);
                    if (data.imageSeeing) {
                        $('<pre class="content" />').appendTo($imageSeeing).text(data.imageSeeing);
                    } else {
                        $('<span class="content">(无)</span>').appendTo($imageSeeing);
                    }

                    const $imageDiagnosis = $('<div class="image-diagnosis content-item" />').appendTo($detail);
                    $('<span class="title">影像诊断：</span>').appendTo($imageDiagnosis);
                    if (data.imageDiagnosis) {
                        $('<pre class="content" />').appendTo($imageDiagnosis).text(data.imageDiagnosis);
                    } else {
                        $('<span class="content">(无)</span>').appendTo($imageDiagnosis);
                    }

                    const $reportDoctor = $('<div class="report-doctor content-item" />').appendTo($detail);
                    $('<span class="title">报告医生：</span>').appendTo($reportDoctor);
                    if (data.reportDoctor) {
                        $('<span class="content" />').appendTo($reportDoctor).text(data.reportDoctor);
                    } else {
                        $('<span class="content">(无)</span>').appendTo($reportDoctor);
                    }

                    $('<span class="title">报告日期：</span>').appendTo($reportDoctor);
                    if (data.reportTime) {
                        $('<span class="content" />').appendTo($reportDoctor).text(ris.formatDateTime(data.reportTime));
                    } else {
                        $('<span class="content">(无)</span>').appendTo($reportDoctor);
                    }

                    const $auditDoctor = $('<div class="audit-doctor content-item" />').appendTo($detail);
                    $('<span class="title">审核医生：</span>').appendTo($auditDoctor);
                    if (data.auditDoctor) {
                        $('<span class="content" />').appendTo($auditDoctor).text(data.auditDoctor);
                    } else {
                        $('<span class="content">(无)</span>').appendTo($auditDoctor);
                    }

                    $('<span class="title">审核日期：</span>').appendTo($auditDoctor);
                    if (data.auditTime) {
                        $('<span class="content" />').appendTo($auditDoctor).text(ris.formatDateTime(data.auditTime));
                    } else {
                        $('<span class="content">(无)</span>').appendTo($auditDoctor);
                    }
                }
            }
        });

        const tools = $.getReportTools($eventEmitter, quickFilter, advancedSearch, dataGrid, null, null, {
            reloadGrid: () => {
                if (reloadGrid instanceof Function) {
                    reloadGrid();
                }
            },
            exportData: (func) => {
                if (exportData instanceof Function) {
                    exportData(func);
                }
            }
        });

        const toolbar = $('.toolbar').dxToolbar({}).dxToolbar('instance');
        //判断是否已经启用了自动刷新
        tools.autoRefresh.options.text = autoRefresh('reportRefreshInterval', 'reportInterval', () => {
            if (reloadGrid instanceof Function) {
                reloadGrid();
            }
        }, true);
        tools.refreshSetting.options.items = [tools.autoRefresh.options, tools.refreshInterval.options]
        //设置打印
        tools.print.options.items = [tools.formalPrint.options, tools.temporarilyPrint.options];
        tools.collect.options.items = [tools.collectTo.options, tools.cancelCollect.options];
        toolbar.option('items', [tools.write, tools.audit, tools.view, tools.delete, tools.viewImage, tools.print, tools.printReport2, tools.collect, tools.remake, tools.refresh, tools.refreshSetting]);
        gridOperations.push(tools.view, tools.viewImage, tools.open, tools.write, tools.audit, tools.delete, tools.printReport, tools.printReport2, tools.applyConsultation, {
            ...tools.collectTo, options: {
                ...tools.collectTo.options,
                icon: 'like'
            }
        }, tools.remake);
        gridContextMenuItems.push(tools.view, tools.viewImage, tools.open, tools.write, tools.audit, tools.delete, tools.printReport, tools.printReport2,
            tools.outputImage, tools.relayImage, tools.examEvent, tools.export, tools.disassemble, tools.transfer, tools.markFollowUp,
            tools.followUpRecord, tools.revisit, tools.eApply, tools.eMedical, tools.applyConsultation, {
            ...tools.collectTo, options: {
                ...tools.collectTo.options,
                icon: 'like'
            }
        }, tools.remake);
        $.get('/api/report/get-advanced-search-view').then(result => {
            if (result.success) {
                if (result.view) {
                    advancedSearch.updateView(result.view, result.data);
                }
            }
        });
    });
})();
